package com.afc.struts.bustle.data;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Vector;

import javax.xml.bind.annotation.XmlRootElement;

import org.apache.commons.beanutils.BeanUtils;

import com.afc.struts.bustle.commons.JsonParser;
import com.afc.struts.bustle.commons.Mapper;
import com.afc.struts.bustle.commons.RestDtoDaoProxy;
import com.afc.struts.bustle.commons.http.TypeToJsonHttpConverter;
import com.afc.struts.bustle.model.ProductDto;

public class ProductDao extends RestDtoDaoProxy<Integer, ProductDto>
{
  public ProductDao()
  {
    super("localhost", 8080, "product", new JsonParser(), new TypeToJsonHttpConverter<>(ProductDto.class), ProductDto.class, new Mapper<ProductDto, ProductDto>()
      {
        @Override
        public ProductDto map(ProductDto aSource, ProductDto aDestination)
        {
          try
          {
            BeanUtils.copyProperties(aDestination, aSource);
          }
          catch (IllegalAccessException | InvocationTargetException anException)
          {
            throw new RuntimeException("Unable copy ProductDto " + aSource, anException);
          }
          return aDestination;
        }
      });
  }

  @Override
  protected List<ProductDto> retrieveAllFrom(String aResult)
  {
    return parser.parse(ProductDtoList.class, aResult).getProduct();
  }

  static public ProductDao getInstance()
  {
    return INSTANCE;
  }

  static private final ProductDao INSTANCE = new ProductDao();

  @XmlRootElement(name = "products")
  static public class ProductDtoList
  {
    public List<ProductDto> getProduct()
    {
      return product;
    }

    public void setProduct(List<ProductDto> aList)
    {
      product = aList;
    }

    protected List<ProductDto> product = new Vector<>();
  }
}
